package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.constant.RedisConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Reference
    SetmealService setmealService;

    @Autowired
    JedisPool jedisPool;

    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile) {

        try {
            //原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            //获取后缀名
            String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼接
            String uuid = UUID.randomUUID().toString().replace("-", "");

            String uploadFileName = uuid + extendName;
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), uploadFileName);
            //执行到此说明文件已经上传完成,把图片名称存储到redis中,sadd命令就是用来操作set集合的.
            /*
            * 参数1:set集合的名称
            * 参数2:图片名称
            * */
            jedisPool.getResource().sadd(RedisConst.SETMEAL_PIC_RESOURCES,uploadFileName);

            return new Result(true, MessageConst.PIC_UPLOAD_SUCCESS, uploadFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConst.PIC_UPLOAD_FAIL);
        }
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        try {
            setmealService.add(setmeal, checkgroupIds);
            return new Result(true, MessageConst.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.getStackTrace();
            return new Result(false, MessageConst.ADD_SETMEAL_FAIL);
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = setmealService.findPage(queryPageBean);
        return pageResult;
    }
}
